# -*- coding: utf-8 -*-
import binascii
import sys
import time

from PySide6.QtCore import Signal, Qt, QTimer, QThread
from PySide6.QtGui import QKeySequence, QShortcut, QColor, QFont
from PySide6.QtWidgets import QMainWindow, QMessageBox, QApplication, QTableWidgetItem, QFileDialog
from loguru import logger

from utils.strTools import ProcessMSToHHMMSS, append_or_blank, format_system_time, parse_bit_flags, \
    convert_hex_to_voltage, convert_hex_to_temperature
from utils.csvHandler import CsvHandler
from windowUI.iICDtcParse_ui import Ui_IICDtcParseMainWindow


class IICDtcParseWindow(QMainWindow, Ui_IICDtcParseMainWindow):
    """
    DTC解析
    """
    # 声明带一个字典类型参数的信号
    iICDtcParseSignal = Signal(dict)

    def __init__(self):
        super().__init__()
        # 加载UI
        self.setupUi(self)
        # 连接信号与槽
        self.SignalConnectInit()
        # 创建定时器
        self.TimerInit()
        # 添加快捷键
        self.ShortcutFun()
        # 引入公共程序
        from utils.common import commonProgram
        # 引入配置文件
        self.myConfig = commonProgram.EnableConfigHandler()
        print('IICDtcParseWindow get config Version', self.myConfig.version)
        # 引入可控串口信息窗口
        # self.serialPortWin = commonProgram.EnableFt4222(winSignal=self.iICDtcParseSignal)

    def CleanupSelf(self):
        """
        清理当前窗口并关闭，由其他其他程序调用
        :return:
        """
        try:
            self.close()  # 关闭当前窗口
            self.deleteLater()  # 释放子窗口资源
            print("PluginWindow.__del__.ok")
        except Exception as err:
            print("PluginWindow.__del__.error", err)

    def SignalConnectInit(self):
        """
        连接来自UI对象的信号与槽
        :return:
        """
        # QPushButton
        self.btnParseDtc.clicked.connect(self.ParseDtcFun)
        self.lineEditDtcInfo.textChanged.connect(self.ParseDtcFun)

    def TimerInit(self):
        """
        定时器创建与信号连接
        此处添加了定时器，一定要在 `CleanupSelf`中添加注销操作，否则切换测试项时不会失效，会一直以子线程运行
        :return:
        """
        pass

    def ShortcutFun(self):
        """
        快捷键 F11 全屏
        快捷键 F5 清屏
        :return:
        """
        # 快捷键 F11
        self.screenStatus = 'Normal'
        screenShortcut = QShortcut(QKeySequence(Qt.Key_F11), self)
        screenShortcut.activated.connect(self.WindowSizeFun)
        self.setToolTip('全屏与退出全屏：\n               双击 或者 F11')
        # 快捷键 F5
        # screenShortcut2 = QShortcut(QKeySequence(Qt.Key_F5), self)
        # screenShortcut2.activated.connect(self.CleanFun)

    def WindowSizeFun(self):
        """
        控制窗口尺寸，此处为原大小（最小UI布局）或者全屏
        :return:
        """
        if self.screenStatus == 'Normal':
            self.showFullScreen()
            self.screenStatus = 'FullScreen'
        else:
            self.showNormal()
            self.screenStatus = 'Normal'

    def SendDataHandle(self, dataDict: dict):
        """
        发送信号或数据处理函数
        :param dataDict:
        :return:
        """
        # 发送信号处理
        dataObj = dataDict.get('data', '')
        typeValue = dataDict.get('type', 'null').strip()
        # 本窗口发送数据
        self.iICDtcParseSignal.emit(dataDict)
        # do something
        logger.info(f"{typeValue} \t {dataObj}")

    def ParseDtcFun(self):
        dtcText = self.lineEditDtcInfo.text().strip()
        if len(dtcText.strip()) < 2:
            # QMessageBox.warning(self, "空数据", f"请输入正确的DTC内容！--> {dtcText}")
            return None
        try:
            if '0x' in dtcText.lower():
                # 去掉 '0x' 前缀，并分割字符串
                dtcText = dtcText.replace('0x', '').split()
                logger.info(f"去掉0x --> {dtcText}")
            else:
                dtcText = dtcText.split()
            logger.info(f"dtcText --> {dtcText}")
            # 将每个十六进制值转换为二进制字符串，并去掉 '0b' 前缀
            binary_values = [bin(int(value, 16))[2:].zfill(8) for value in dtcText]
            self.labelBin.setText(str(binary_values))
            # 将每个十六进制值转换为二进制字符串，并去掉 '0b' 前缀
            binary_values = [list(bin(int(value, 16))[2:].zfill(8)) for value in dtcText]
            logger.info(f"解析为二进制 --> {binary_values}")
            row_position = 0
            rowDiffer = self.tableWidget.rowCount() - len(binary_values)
            for row_position, byte_value in enumerate(binary_values):
                if row_position >= self.tableWidget.rowCount():
                    self.tableWidget.insertRow(row_position)
                for index, bit_value in enumerate(byte_value):
                    tableWidgetItem = self.tableWidget.item(row_position, index)
                    if tableWidgetItem == None:
                        tableWidgetItem = QTableWidgetItem()
                    if '1' == bit_value:
                        tableWidgetItem.setForeground(QColor(255, 33, 33, 255))
                        tableWidgetItem.setCheckState(Qt.CheckState.Checked)
                    else:
                        tableWidgetItem.setForeground(QColor(0, 0, 0, 255))
                        tableWidgetItem.setCheckState(Qt.CheckState.Unchecked)
                    if rowDiffer < 0:
                        self.tableWidget.setItem(row_position, index, tableWidgetItem)
            # print(self.tableWidget.rowCount(), row_position, self.tableWidget.rowCount() - row_position - 1)
            if rowDiffer > 0:
                for add_value in range(self.tableWidget.rowCount() - row_position - 1):
                    for index in range(self.tableWidget.columnCount()):
                        tableWidgetItem = self.tableWidget.item(row_position + add_value + 1, index)
                        tableWidgetItem.setForeground(QColor(0, 0, 0, 255))
                        tableWidgetItem.setCheckState(Qt.CheckState.Unchecked)
            myText = f"解析完成：{binary_values}"
            dictData = {"data": myText, "type": f"status_show"}
            self.SendDataHandle(dictData)
            self.statusbar.showMessage(myText)
        except Exception as e:
            logger.error(e)

    # def closeEvent(self, event):
    #     """
    #     防止误触关闭程序
    #     :param event:
    #     :return:
    #     """
    #     # 创建一个确认退出的对话框
    #     reply = QMessageBox.question(
    #         self, "Confirmation", "Are you sure you want to exit?",
    #         QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, QMessageBox.StandardButton.No
    #     )
    #     if reply == QMessageBox.StandardButton.Yes:
    #         self.CleanupSelf()
    #         # 用户确认退出，关闭应用
    #         event.accept()
    #     else:
    #         event.ignore()


# 程序入口，测试当前插件文件使用
if __name__ == "__main__":
    app = QApplication(sys.argv)
    font = QFont("宋体")
    pointsize = font.pointSize()
    font.setPixelSize(int(pointsize * 90 / 72))
    app.setFont(font)
    myWindow = IICDtcParseWindow()
    myWindow.show()
    sys.exit(app.exec())
